<template>
  <view class="container">
    <!-- 标题栏 -->
    <view class="header">
      <image class="logo" src="/static/ai-logo.png" mode="aspectFit" />
      <text class="title">AI 智能助手</text>
    </view>

    <!-- 对话历史区域 -->
    <scroll-view class="chat-box" scroll-y="true" :scroll-top="scrollTop" scroll-with-animation>
      <view v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
        <image class="avatar" :src="msg.role === 'user' ? 'http://lbwnb123.oss-cn-beijing.aliyuncs.com/%E9%9D%92%E5%9F%8E/%E6%B6%88%E6%81%AF/%E9%A3%8E%E5%90%B9%E9%BA%A6%E6%B5%AA.jpg' : 'https://tse4-mm.cn.bing.net/th/id/OIP-C.5e8N4UXuaa4UE8WzszYilgHaFj?rs=1&pid=ImgDetMain'" />
        <view class="message-content">
          <text class="sender-name">{{ msg.role === 'user' ? '你' : 'AI助手' }}</text>
          <text class="message-text" v-if="!msg.streaming">{{ msg.content }}</text>
          <text class="message-text" v-else>{{ displayedContent[index] }}</text>
        </view>
      </view>
      <view v-if="isLoading" class="loading">
        <image class="typing-indicator" src="/static/typing.gif" mode="aspectFit" />
        <text>AI正在思考...</text>
      </view>
    </scroll-view>

    <!-- 输入框和发送按钮 -->
    <view class="input-area">
      <input
          class="input"
          v-model="userInput"
          placeholder="输入消息..."
          @confirm="sendMessage"
          :disabled="isLoading"
          placeholder-class="placeholder"
      />
      <button
          class="send-btn"
          @click="sendMessage"
          :disabled="isLoading || !userInput.trim()"
          :style="{background: isLoading || !userInput.trim() ? '#ccc' : '#4a90e2'}"
      >
        <image v-if="!isLoading" src="/static/send-icon.png" class="send-icon" />
        <image v-else src="/static/loading-spinner.gif" class="loading-icon" />
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      messages: [
        {
          role: 'assistant',
          content: '你好！我是AI助手，有什么可以帮您的吗？',
          streaming: false
        }
      ],
      displayedContent: {}, // 用于存储动态显示的内容
      userInput: '',
      isLoading: false,
      scrollTop: 0,
      typingInterval: null,
      Baseurl: "https://dseek.aikeji.vip",
      Skey: "sk-AmDeSkRHlSvXqXBMd9KKVkucjkvSfOheFklJx1DnQKxPFtSv"
    };
  },
  methods: {
    async sendMessage() {
      if (!this.userInput.trim() || this.isLoading) return;

      // 添加用户消息
      const userMessage = this.userInput;
      this.messages.push({
        role: 'user',
        content: userMessage,
        streaming: false
      });
      this.userInput = '';
      this.scrollToBottom();

      // 调用API
      this.isLoading = true;
      try {
        // 先添加一个空消息用于动态显示
        const aiMessageIndex = this.messages.push({
          role: 'assistant',
          content: '',
          streaming: true
        }) - 1;

        // 初始化动态显示内容
        this.$set(this.displayedContent, aiMessageIndex, '');

        // 调用API
        const aiResponse = await this.callDeepSeekAPI(userMessage);

        // 模拟逐字显示效果
        await this.typewriterEffect(aiMessageIndex, aiResponse);

      } catch (error) {
        console.error('API Error:', error);
        uni.showToast({
          title: '请求失败: ' + (error.message || '未知错误'),
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },

    // 打字机效果
    typewriterEffect(messageIndex, fullText) {
      return new Promise((resolve) => {
        let i = 0;
        const speed = 20; // 打字速度(ms)

        const typing = () => {
          if (i < fullText.length) {
            this.displayedContent[messageIndex] = fullText.substring(0, i + 1);
            i++;
            this.scrollToBottom();
            setTimeout(typing, speed);
          } else {
            // 完成打字后更新消息状态
            this.messages[messageIndex].streaming = false;
            this.messages[messageIndex].content = fullText;
            resolve();
          }
        };

        typing();
      });
    },

    async callDeepSeekAPI(userMessage) {
      let response;
      try {
        response = await uni.request({
          url: this.Baseurl + "/v1/chat/completions",
          method: 'POST',
          header: {
            'Accept': 'application/json',
            'Authorization': `Bearer ${this.Skey}`,
            'Content-Type': 'application/json'
          },
          data: {
            model: "deepseek-v3",
            messages: [
              ...this.messages.filter(m => m.role !== 'system'),
              { role: 'user', content: userMessage }
            ],
            temperature: 0.7,
            stream: false // 确保API返回完整响应
          },
          timeout: 20000
        });

        const res = Array.isArray(response) ? response[1] : response;

        if (!res) throw new Error('Empty response');
        if (res.statusCode !== 200) {
          throw new Error(res.data?.error?.message || `HTTP ${res.statusCode}`);
        }

        return res.data?.choices?.[0]?.message?.content || '未收到有效回复';

      } catch (error) {
        console.error('API错误:', error);
        throw new Error(`AI服务暂不可用: ${error.message}`);
      }
    },

    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollTop = 999999;
      });
    }
  },
  beforeDestroy() {
    if (this.typingInterval) {
      clearInterval(this.typingInterval);
    }
  }
};
</script>

<style>
/* 基础样式 */
page {
  background-color: #f8f9fa;
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 0;
  background-color: #f8f9fa;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background-color: #4a90e2;
  color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.logo {
  width: 32px;
  height: 32px;
  margin-right: 10px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

/* 聊天区域样式 */
.chat-box {
  flex: 1;
  padding: 15px;
  overflow: auto;
  background-color: #f8f9fa;
}

.message {
  display: flex;
  margin-bottom: 20px;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  flex-shrink: 0;
  align-self: flex-start;
}

.message-content {
  max-width: 75%;
  display: flex;
  flex-direction: column;
}

.sender-name {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.message-text {
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 15px;
  line-height: 1.5;
  word-break: break-word;
}

.message.user {
  justify-content: flex-end;
}

.message.user .message-content {
  align-items: flex-end;
}

.message.user .message-text {
  background-color: #4a90e2;
  color: white;
  border-bottom-right-radius: 4px;
}

.message.assistant .message-text {
  background-color: white;
  color: #333;
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.loading {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  color: #666;
  font-size: 14px;
}

.typing-indicator {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

/* 输入区域样式 */
.input-area {
  display: flex;
  padding: 15px;
  background-color: white;
  border-top: 1px solid #e0e0e0;
  align-items: center;
}

.input {
  flex: 1;
  height: 45px;
  padding: 0 15px;
  background-color: #f0f2f5;
  border-radius: 25px;
  font-size: 15px;
  border: none;
  outline: none;
}

.placeholder {
  color: #999;
}

.send-btn {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  margin-left: 10px;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  border: none;
}

.send-icon {
  width: 24px;
  height: 24px;
}

.loading-icon {
  width: 20px;
  height: 20px;
}
</style>
